package com.iflyings.android.convention

import com.android.build.api.dsl.ApplicationExtension
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getByType
import java.io.FileInputStream
import java.text.SimpleDateFormat
import java.util.*

private fun releaseTime(): Int {
    return SimpleDateFormat("yyyyMMdd").format(Date()).toInt()
}

internal fun Project.configureAndroidApplication(commonExtension: ApplicationExtension, ) {
    val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")

    commonExtension.apply {

        compileSdk = libs.findVersion("compileSdkVersion").get().toString().toInt()

        signingConfigs {
            create("rk_device") {
                val keystorePropertiesFile = rootProject.file("local.properties")
                val keystoreProperties = Properties()
                keystoreProperties.load(FileInputStream(keystorePropertiesFile))

                keyAlias = keystoreProperties["keyAlias"] as String
                keyPassword = keystoreProperties["keyPassword"] as String
                storeFile = file(keystoreProperties["storeFile"] as String)
                storePassword = keystoreProperties["storePassword"] as String
            }
        }

        defaultConfig {
            val version = releaseTime()
            minSdk = libs.findVersion("minSdkVersion").get().toString().toInt()
            targetSdk = libs.findVersion("targetSdkVersion").get().toString().toInt()
            versionCode = version
            versionName = "1.0.$version"
            testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        }

        buildTypes {
            debug {
                signingConfig = signingConfigs.getByName("rk_device")
            }
            release {
                signingConfig = signingConfigs.getByName("rk_device")
                isMinifyEnabled = false //混淆
                isShrinkResources = false // 移除无用的resource文件
                proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
            }
        }

        dependencies {
            add("implementation", libs.findBundle("androidx").get())
            add("testImplementation", libs.findLibrary("junit").get())
            add("androidTestImplementation", libs.findBundle("test-androidx").get())
        }
    }
}